package com.dgw.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dgw.entity.Course;
import com.dgw.entity.StudentCourseRel;
import com.dgw.enums.ResultEnum;
import com.dgw.exception.MyException;
import com.dgw.mapper.CourseMapper;
import com.dgw.mapper.StudentCourseRelMapper;
import com.dgw.service.CourseService;
import com.dgw.utils.PageRows;
import com.dgw.utils.StringUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class CourseServiceImpl implements CourseService{
	
	@Autowired
	private CourseMapper courseMapper;
	
	@Autowired
	private StudentCourseRelMapper studentCourseRelMapper;

	@SuppressWarnings("unchecked")
	@Override
	public PageInfo<Course> selectByPageAndSelections(String keyword, PageRows pageRows) {
		PageHelper.startPage(pageRows.getCurrentPage(), pageRows.getPageSize());
		List<Course> courses = courseMapper.selectByPageAndSelections(keyword);
		PageInfo<Course> pageInfo = new PageInfo<>(courses);
		return pageInfo;
	}

	@Override
	public int insert(Course course) {
		course.setcId(StringUtil.uuid());
		return courseMapper.insert(course);
	}

	@Override
	public int updateByPrimaryKeySelective(Course course) {
		return courseMapper.updateByPrimaryKeySelective(course);
	}

	@Override
	public Course selectByPrimaryKey(String cId) {
		return courseMapper.selectByPrimaryKey(cId);
	}

	@Override
	public List<Course> selectAll() {
		return courseMapper.selectByPageAndSelections(null);
	}

	@Override
	public List<StudentCourseRel> selectStudentCourseRel(String sId) {
		return studentCourseRelMapper.selectStudentCourseRel(sId);
	}

	@Override
	public int updateStudentCourse(String sId, String[] cIds) {
		//1,删除该学生的所有课程
		List<StudentCourseRel> studentCourses = studentCourseRelMapper.selectStudentCourseRel(sId);
		if(studentCourses!=null && studentCourses.size() >0){
			int deleteBySId= studentCourseRelMapper.deleteBySId(sId);
			if(deleteBySId<=0){
				return 0;
			}
		}
		//2，保存新选中的课程
		for(String cId:cIds){
			StudentCourseRel studentCourseRel = new StudentCourseRel();
			studentCourseRel.setsId(sId);
			studentCourseRel.setcId(cId);
			int insert = studentCourseRelMapper.insert(studentCourseRel);
			if(insert<=0){
				throw new MyException(ResultEnum.UNKOWN);
			}
		}
		return 1;
	}
}
